package com.android.guoqi.sms

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat

class PermissionsUtil(private val context: Activity) {

    /**
     * 检查权限是否已请求到 (6.0)
     */
    fun checkPermissions(permissions: Array<String>) {
        // 版本兼容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                // 判断缺失哪些必要权限
                && lacksPermissions(permissions)) {
            // 如果缺失,则申请
            requestPermissions(permissions)
        }
    }

    /**
     * 判断是否缺失权限集合中的权限
     */
    private fun lacksPermissions(permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (lacksPermission(permission)) {
                return true
            }
        }
        return false
    }

    /**
     * 判断是否缺少某个权限
     */
    private fun lacksPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED
    }

    /**
     * 请求权限
     */
    private fun requestPermissions(permissions: Array<String>) {
        ActivityCompat.requestPermissions(context, permissions, PERMISSION_REQUEST_CODE)
    }

    /**
     * 启动应用的设置,进入手动配置权限页面
     */
    private fun startAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", context.packageName, null)
        intent.data = uri
        context.startActivity(intent)
    }

    fun showMissingPermissionDialog() {
        startAppSettings()
    }

    companion object {
        var PERMISSION_REQUEST_CODE = 0
        var PERMISSIONS = arrayOf(Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS)
    }
}
